# -*- coding: UTF-8 -*-

from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.properties import NumericProperty
from model.gamestate import Phase
from kivy.properties import StringProperty
from kivy.uix.popup import Popup
from kivy.clock import Clock

import model.gamestate

from ui.hat_widget import HatWidget


class ChangeNamePopup(Popup):
    def __init__(self, root, **kwargs):
        self.root = root
        self.player = None
        super(ChangeNamePopup, self).__init__(**kwargs)

    def change_text(self):
        name = self.name_input.text.strip()
        if self.player is not None:
            self.player.name = name
        was_same_name = False
        for player in self.root.game_state.players.players:
            if player.name == name:
                if not was_same_name:
                    was_same_name = True
                else:
                    self.ok_button.enabled = False
                    return
        self.ok_button.enabled = True

    def change_name(self):
        if not self.ok_button.enabled:
            return
        self.player.name = self.name_input.text.strip()
        self.root.player_explain = '{}. {}'.format(str(self.root.pair[0].idx +
                                                       1),
                                                   self.root.pair[0].name)
        self.root.player_guess = '{}. {}'.format(str(self.root.pair[1].idx +
                                                     1),
                                                 self.root.pair[1].name)
        self.dismiss()

    def on_open(self):
        self.name_input.text = self.player.name
        self.name_input.select_all()
        self.name_input.focus = True
        self.root.presenter.adapter.show_keyboard()

    def on_dismiss(self):
        self.name_input.focus = False
        self.root.presenter.adapter.hide_keyboard()


class FromToWidget(HatWidget):
    player_explain = StringProperty()
    player_guess = StringProperty()
    round_num = NumericProperty()
    time_remaining = StringProperty()
    button_text = StringProperty()

    def __init__(self, game_state, presenter, **kwargs):
        """ Construct FromTo screen
        need:
        valid gamestate.hat.words
        valid gamestate.game_round.player_pair or gamestate.game_round = None
        valid gamestate.players
        do:
        creates gamestate.game_round (if None)
        changes phase to BEFORE_ROUND
        Args:
        self.game_state: (GameState)
        presenter: (Presenter) main view presenter
        """

        self.game_state = game_state
        if self.game_state.round_num is None:
            self.game_state.round_num = 0
            self.game_state.shall_change = True
        self.words_remaining = len(self.game_state.hat.words)
        self.presenter = presenter
        if self.game_state.rounds is None:
            self.game_state.rounds = []
        self.pair = [None, None]
        if self.game_state.players.players_select_strategy.is_pair_strategy():
            self.delete_butt_text = _('Remove current pair')
        else:
            self.delete_butt_text = _('Remove explaining player')

        self.change_name_popup = ChangeNamePopup(self)

        self.create_round()

        if self.game_state.players.players[0].name == self.pair[0].name and\
           self.game_state.shall_change:
            self.game_state.round_num += 1

        self.round_num = self.game_state.round_num
        self.game_state.shall_change = True
        self.presenter.adapter.hide_keyboard()
        super(FromToWidget, self).__init__(**kwargs)

        self.redraw_delete_button()
        self.redraw_skip_button()

    def go_to_guess(self, dt):
        self.presenter.change_phase(model.gamestate.Phase.GUESS_WORD)

    def create_round(self):
        if (self.game_state.game_round is not None and
            self.game_state.game_round.time_left_sec <
                self.game_state.settings.time_per_round_sec):
            if (self.game_state.game_round.time_left_sec <= 0):
                Clock.schedule_once(self.go_to_guess, -1)
            self.button_text = _('Resume')
            self.time_remaining = _('{} sec left').format(str(int(
                self.game_state.game_round.time_left_sec)))
        else:
            self.button_text = _('Go!')
            if self.game_state.game_round is None:
                self.game_state.game_round = \
                    model.gamestate.GameRound(self.game_state.settings.
                                              time_per_round_sec,
                                              [], None,
                                              self.game_state.players.
                                              players_select_strategy.
                                              get_next_pair())
            self.time_remaining = ''
        self.pair = self.game_state.game_round.players_pair
        self.set_players_idx()
        self.player_explain = u'{}. {}'.format(str(self.pair[0].idx + 1),
                                               self.pair[0].name)
        self.player_guess = u'{}. {}'.format(str(self.pair[1].idx + 1),
                                             self.pair[1].name)

    def delete(self):
        self.delete_player(self.game_state.game_round.players_pair[0])
        if self.game_state.players.players_select_strategy.is_pair_strategy():
            self.delete_player(self.game_state.game_round.players_pair[1])

        self.game_state.players.players_select_strategy.is_players_deleted =\
            True

        self.game_state.shall_change = False
        self.skip()
        self.redraw_delete_button()

    def delete_player(self, player):
        for i in range(len(self.game_state.players.players)):
            if self.game_state.players.players[i] == player:
                del (self.game_state.players.players[i])
                return
        self.redraw_delete_button()

    def finish(self, finish=False):
        """ changes phase to BEFORE_ROUND
        call on release 'Старт' button
        """
        self.game_state.is_paused = False

        next_phase = Phase.CURRES if finish else Phase.BEFORE_ROUND
        self.presenter.change_phase(next_phase)

    def open_popup(self, player):
        self.change_name_popup.player = player
        self.change_name_popup.open()

    def prev_view(self):
        self.presenter.change_phase(model.gamestate.Phase.PLAYERS_ORDER)

    def redraw_delete_button(self):
        self.delete_button.enabled =\
            (len(self.game_state.players.players) > 2 and
             self.presenter.settings.game.may_delete_player)

    def redraw_skip_button(self):
        self.skip_button.enabled = self.presenter.settings.game.may_skip_turn

    def set_players_idx(self):
        idx = 0
        for player in self.game_state.players.players:
            player.idx = idx
            idx += 1

    def skip(self):
        self.game_state.rounds.append(self.game_state.game_round)
        self.game_state.game_round = None
        self.create_round()

        if self.game_state.players.players[0].name == self.pair[0].name and\
                self.game_state.shall_change:
                    self.round_num += 1
                    self.game_state.round_num += 1
        self.game_state.shall_change = True

    def update(self):
        self.redraw_delete_button()
        self.redraw_skip_button()
